# -*- coding: utf-8 -*-
# created on 2016/11/30

from mathsolver.functions.base import *
from sympy import Tuple, Interval


class FuShuTOFEq(BaseFunction):
    def solver(self, *args):
        f1, f2 = args[0].sympify()
        expr = f1 - f2
        known = self.known
        symbols = expr.free_symbols
        answers = []
        for name in known:
            if isinstance(name, (Tuple, tuple)):
                new_name = set(name)
                if new_name & symbols <= new_name:
                    values = known[name]
                    for value in values:
                        value = list(value)
                        for sym, v in zip(name, value):
                            v_index = value.index(v)
                            if isinstance(v, Interval):
                                value[v_index] = sym
                        symbol_value = dict([(sym, v) for sym, v in zip(name, value)])
                        answers.append(symbol_value)
            else:
                if name in symbols:
                    values = known[name]
                    if not isinstance(values, (Union, Interval)):
                        values = list(known[name])
                        symbol_value = {name: values}
                        answers.append(symbol_value)
        expr_values = []
        for ans in answers:
            new_expr = expr
            new_expr = new_expr.subs(ans)
            new_expr = new_expr.expand().simplify()
            expr_values.append(new_expr)
        expr_values = set(expr_values)
        expr_values = list(expr_values)
        if len(expr_values) == 1:
            expr_value = expr_values[0]
            if expr_value == 0:
                self.output.append(BaseVariable(True))
            else:
                self.output.append(BaseVariable(False))
        else:
            self.output.append(BaseVariable(False))
        return self
